/*
 * sharedMemory.c
 *
 *  Created on: Mar 3, 2013
 *      Author: abrahamsantini
 */


#include "semaphore.h"
#include "sharedMemory.h"
#include <time.h>
#include <stdlib.h>


int init_sharedMemory(sharedMemory_t *sm) {
	sm -> topOfStack = 0;
	int temp;
	for (temp = 0; temp < 10; temp++) {
		sm->stack[temp] = 0;
	}
	srand(time(NULL));
	int r = rand() % 100;
	sm -> calcValue = r;
	semaphore_init(&sm->calcMutex, 1);
	semaphore_init(&sm->tosMutex,1);
	semaphore_init(&sm->stackMutex,1);
	return 0;
}

int init_value(sharedMemory_t *sm) {
	srand(time(NULL));
	int r = rand() % 100;

	sm -> calcValue = r;


	return 0;
}

int init_tos(sharedMemory_t *sm) {
	int ret = sm -> topOfStack = 0;
	if (sm -> topOfStack != 0 ) {
		ret = -1;
	}
	return ret;
}
int getValue(sharedMemory_t *sm) {
	int ret;
	if(sm->calcMutex.count == 0) {
		ret = sm -> calcValue;
	} else {
		ret = -1;
	}

	return 	ret;


}

int getTos(sharedMemory_t *sm) {
	return sm -> topOfStack;
}

int pushStack(sharedMemory_t *sm, int the_value) {
	int ret;
	if(sm -> topOfStack < (sizeof(sm -> stack)/sizeof(sm->stack[0]))){
		sm -> stack[sm -> topOfStack++] = the_value;
		ret = the_value;
	} else {
		ret = -1;
	}
	return ret;
}

int popStack(sharedMemory_t *sm) {
	int ret;
	if(sm -> topOfStack > 0) {
		sm->topOfStack--;
		ret = sm->stack[sm -> topOfStack];
		sm->stack[sm->topOfStack] = 0;

	} else {
		ret = -1;
	}
	return ret;
}


